# -*- coding: utf-8
import gzip
import os
import shutil
import tarfile

from flask import Flask

app = Flask(__name__)


def allowed_map_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1] in ['tar', 'png', 'yaml', 'pgm']


def allowed_music_file(filename):
    return '.' in filename and \
           filename.rsplit('.', 1)[1] in ["mp3", "wav"]


# 复制函数
def copyfile(srcfile, dstpath):
    if not os.path.isfile(srcfile):
        return str("%s not exist!" % (srcfile))
    else:
        fpath, fname = os.path.split(srcfile)  # 分离文件名和路径
        if not os.path.exists(dstpath):
            os.makedirs(dstpath)  # 创建路径
        shutil.copy(srcfile, dstpath + fname)  # 复制文件
        return ""


def ssh_shutdown(hostname="172.20.0.100", port=22, username="lyric", password="1234.com", timeout=2, param="-h",
                 mode=1):
    """利用ssh远程关闭宿主机
    """
    import paramiko, time

    ssh = paramiko.SSHClient()
    know_host = paramiko.AutoAddPolicy()
    ssh.set_missing_host_key_policy(know_host)

    ssh.connect(
        hostname=hostname,
        port=port,
        username=username,
        password=password
    )

    ret = False
    # 硬重启
    if mode == 1:
        # sudo -S参数能用管道（上一个命令的 stdout 接到下一个命令的 stdin）传递密码等参数
        ssh.exec_command("echo {} | sudo -S shutdown {} now".format(password, param))
        ret = True

    # 软重启
    elif mode == 2:
        ssh.exec_command("echo {} | sudo -S docker restart ros_env-run".format(password))
        ssh.exec_command("echo {} | sudo -S docker restart ros_env-depth_camera".format(password))
        ret = True

    # 仅重启USB相机及其他传感器节点
    elif mode == 3:
        ssh.exec_command("echo {} | sudo -S docker restart ros_env-depth_camera".format(password))
        ret = True
    else:
        ret = False

    time.sleep(timeout)  # 保证生命周期内可执行完毕
    ssh.close()
    return ret


def del_files(dir_path):
    if os.path.isfile(dir_path):
        try:
            os.remove(dir_path)  # 这个可以删除单个文件，不能删除文件夹
        except BaseException as e:
            return e
    elif os.path.isdir(dir_path):
        file_lis = os.listdir(dir_path)
        for file_name in file_lis:
            # if file_name != 'wibot.log':
            tf = os.path.join(dir_path, file_name)
            del_files(tf)
    return ""


def un_gz(file_name):
    """ungz zip file"""
    f_name = file_name.replace(".tar.gz", "")
    # 获取文件的名称，去掉
    g_file = gzip.GzipFile(file_name)
    # 创建gzip对象
    open(f_name, "wb+").write(g_file.read())
    # gzip对象用read()打开后，写入open()建立的文件里。
    g_file.close()  # 关闭gzip对象


def un_tar(file_name, paths):
    """untar zip file"""
    tar = tarfile.open(file_name)
    names = tar.getnames()

    for name in names:
        tar.extract(name, paths)
    tar.close()
